<style lang="less">
  .no-stowage-trunk-task{
    .split_order {
      color: #FF4949;
    }
  }
</style>

<template>
  <el-dialog class="no-stowage-trunk-task" title="未配载订单列表" :visible.sync="dialogVisible">
    <search-bar label-position="left" label-width="100px" more-display>
      <el-row>
        <el-col :span="8">
          <el-form-item label="发运日期">
            <el-date-picker v-model="noStowageShipmentsDaterange" type="daterange"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货人名称">
            <el-input v-model="searchCondition['LIKE_order.sendContactName']"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货人手机">
            <el-input v-model="searchCondition['LIKE_order.sendContactPhone']"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货人地址">
            <el-input v-model="searchCondition['LIKE_order.sendStreet']"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="到达目的地">
            <el-cascader
              placeholder="请选择配载中心"
              :options="$store.state.initOrganizations"
              :props="{label: 'name',value: 'id'}"
              change-on-select
              v-model="noStowageOrganizations"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运单号">
            <el-input v-model="searchCondition.LIKE_transportationNumber"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="入库状态">
            <el-select v-model="searchCondition.EQ_whetherStorage" placeholder="请选择">
              <el-option
                label="已入库"
                :value="true">
              </el-option>
              <el-option
                label="未入库"
                :value="false">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单号">
            <el-input v-model="searchCondition.EQ_orderNumber"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>
    <el-col :span="24" style="margin-bottom: 10px">
      <el-col :span="12">
        <el-switch
          v-model="orderType"

          >
        </el-switch>
      </el-col>
      <el-col :span="8">
        当前选中：{{totalPoll}}票 {{totalAmount}}件 {{totalWeight}}吨 {{totalVolume}}方
      </el-col>
      <el-col :span="4" style="text-align: right">
        <el-button type="primary" @click="noStowageQuery">查询</el-button>
        <el-button type="primary" @click="noStowageReset">重置</el-button>
      </el-col>
    </el-col>

    <!--列表-->
    <ue-el-table ref="noStowageTable" :data="tableData"
                 highlight-current-row border
                 height="400"
                 current-row-key="id"
                 @select="noStowageSelect"
                 v-loading="listLoading"
                 @selection-change="noStowageSelsChange"
                 :row-class-name="tableRowClassName"
                 style="width: 100%;">
      <el-table-column type="selection" fixed="left" width="55">
      </el-table-column>
      <ue-el-table-tree-column fixed
                               :remote="remoteNoStowage"
                               prop="label"
                               label="订单号"
                               child-num-key="num"
                               width="230">
      </ue-el-table-tree-column>
      <el-table-column show-overflow-tooltip prop="order.shipmentsDate" label="发运日期" width="120">
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="order.cargoNames" label="货物品名" width="120">
      </el-table-column>
      <el-table-column prop="order.packTypeNames" label="包装" width="120">
      </el-table-column>
      <el-table-column prop="order.sendContactName" label="收货人名称" width="160">
      </el-table-column>
      <el-table-column prop="order.sendContactPhone" label="收货人手机" width="160">
      </el-table-column>
      <el-table-column prop="order.sendStreet" label="收货人地址" width="160">
      </el-table-column>
      <el-table-column prop="order.transportationNumber" label="运单号" width="160">
      </el-table-column>
      <el-table-column prop="order.extractTypeName" label="提货状态" width="120">
      </el-table-column>
      <el-table-column label="预计入库" width="120">
      </el-table-column>
      <el-table-column label="入库状态" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.whetherStorage">已入库</span>
          <span v-else>未入库</span>
        </template>
      </el-table-column>
      <el-table-column prop="order.sendTypeName" label="配送方式" width="120">
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="order.sendTime" label="要求到达时间" width="140">
      </el-table-column>
      <el-table-column prop="order.agingName" label="运输方式" width="120">
      </el-table-column>
      <el-table-column prop="order.orderPrice" label="运费(元)" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.pid===null">{{scope.row.order.orderPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="order.paymentTypeName" label="结算方式" width="100">
      </el-table-column>
      <el-table-column prop="order.shipmentsContactName" label="发货人名称" width="160">
      </el-table-column>
      <el-table-column prop="order.shipmentsContactPhone" label="发货人手机" width="160">
      </el-table-column>
      <el-table-column label="备注" width="120">
      </el-table-column>
      <el-table-column fixed="right" prop="order" label="件重体" width="140" :formatter="formatterOrderCargos">
      </el-table-column>
    </ue-el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="ok">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  sendRegionAndNum,
  shipmentsRegionAndNum,
  trunkTasksPageSub
} from '../../api/stowage/TrunkTask';
import { batchAddLoadingListTrunkTask } from '../../api/stowage/LoadingListTrunkTask';
export default {
  name: 'NoStowageTrunkTask',
  componentName: 'NoStowageTrunkTask',
  data () {
    return {
      loadingListRouteId: null,
      sels: [],
      listLoading: false,
      tableData: [],
      noStowageShipmentsDaterange: [],
      noStowageOrganizations: [],
      searchCondition: {
        EQ_orderNumber: null,
        LIKE_transportationNumber: null,
        LT_shipmentsDate: null,
        GT_shipmentsDate: null,
        EQ_whetherStorage: null,
        LIKE_currentSpecialLineIds: null,
        'LIKE_order.sendContactName': null,
        'LIKE_order.sendContactPhone': null,
        'LIKE_order.sendStreet': null
      },
      dialogVisible: false,
      orderType: false,
      totalPoll: 0,
      totalAmount: 0,
      totalWeight: 0,
      totalVolume: 0
    };
  },
  watch: {
    noStowageShipmentsDaterange (val) {
      this.searchCondition.GT_shipmentsDate = val[0] == null ? null : val[0].toJSON();
      this.searchCondition.LT_shipmentsDate = val[1] == null ? null : val[1].toJSON();
    },
    noStowageOrganizations (val) {
      if (val.length > 0) {
        this.searchCondition.LIKE_currentSpecialLineIds = val[val.length - 1];
      }
    },
    orderType (val) {
      this.noStowageSearch('');
    },
    sels (sels) {
      let ids = sels.filter(item => (item.type === 'group' || item.childrenNum > 0)).map(i => i.id);
      let totalAmount = 0;
      let totalWeight = 0;
      let totalVolume = 0;
      let totalPoll = 0;
      sels.forEach(item => {
        if (item.type === 'group') {
          totalAmount += item.amount;
          totalWeight += item.weight;
          totalVolume += item.volume;
          totalPoll += item.num;
        } else {
          if (ids.indexOf(item.parent_id) === -1 && ids.indexOf(item.pid) === -1) {
            totalAmount += item.amount;
            totalWeight += item.weight;
            totalVolume += item.volume;
            totalPoll += (item.childNodeNum || 1);
          }
        }
      });
      this.totalAmount = totalAmount;
      this.totalWeight = totalWeight;
      this.totalVolume = totalVolume;
      this.totalPoll = totalPoll;
    }
  },
  methods: {
    tableRowClassName (row, index) {
      return row.childrenNum > 0 ? 'split_order' : '';
    },
    ok () {
      if (this.loadingListRouteId === null) {
        this.$message.warning('请选择下货地');
        return;
      }
      let o = {};
      Object.keys(this.searchCondition).forEach(k => {
        let ks = k.split('_');
        const split = (ks[1] || '').split('.');
        let vs = split.map((currentValue, index, array) => {
          if (index === split.length - 1) {
            return currentValue;
          } else {
            return 'LEFT_' + currentValue;
          }
        }).join('.');
        o[ks[0] + '_' + vs] = this.searchCondition[k];
      });
      let params = [];
      this.sels.forEach(item => {
        params.push({
          id: item.id,
          type: item.type === 'group' ? (this.orderType ? 'shipments_group' : 'send_group') : (item.childrenNum ? 'parent' : '')
        });
      });
      batchAddLoadingListTrunkTask(this.$ue.objToFilter(o) + ';', this.loadingListRouteId, params)
        .then(res => {
          if (res.data.successFlg) {
            this.dialogVisible = false;
            this.$message.success('移入成功!');
            this.$emit('addTrunkTaskOk');
          }
        });
    },
    show (id) {
      this.dialogVisible = true;
      this.loadingListRouteId = id;
      this.noStowageSearch('');
      this.noStowageReset();
    },
    formatterOrderCargos (row) {
      return row.amount + '件/' + row.weight.toFixed(2) + '吨/' + row.volume.toFixed(2) + '方';
    },
    remoteNoStowage (row, callback) {
      let filters = 'ISNULL_LEFT_loadingListTrunkTask.id;' + this.$ue.objToFilter(this.searchCondition) + ';';
      let orFilters;
      let depth = 0;
      if (row.type === 'group') {
        let o = {};
        Object.keys(this.searchCondition).forEach(k => {
          let ks = k.split('_');
          const split = (ks[1] || '').split('.');
          let vs = split.map((currentValue, index, array) => {
            if (index === split.length - 1) {
              return currentValue;
            } else {
              return 'LEFT_' + currentValue;
            }
          }).join('.');
          o[ks[0] + '_LEFT_children.' + vs] = this.searchCondition[k];
        });
        orFilters = ';ISNULL_LEFT_children.LEFT_loadingListTrunkTask.id;' + this.$ue.objToFilter(o) + ';';
        filters += ';ISNULL_childrenNum;ISNULL_parent;';
        if (!this.orderType) {
          filters += ';EQ_LEFT_order.sendCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.LEFT_order.sendCountyId=' + row.id + ';';
        } else {
          filters += ';EQ_LEFT_order.shipmentsCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.LEFT_order.shipmentsCountyId=' + row.id + ';';
        }
        depth = 1;
      } else {
        filters += 'EQ_parent.id=' + row.id;
        if (!this.orderType) {
          filters += ';EQ_LEFT_order.sendCountyId=' + row.parent_id + ';';
        } else {
          filters += ';EQ_LEFT_order.shipmentsCountyId=' + row.parent_id + ';';
        }
        depth = 2;
      }
      this.trunkTasks(
        filters,
        orFilters,
        '-shipmentsDate',
        data => {
          let items = data.detailModelList;
          items.forEach(item => {
            item.parent_id = row.id;
            item.depth = depth;
            if (item.childrenNum) {
              item.num = item.childrenNum;
              item.label += ('(拆-' + item.childrenNum + ')');
            }
          });
          callback(items);
        }
      );
    },
    trunkTasks (filter, orFilters, sorts, success) {
      trunkTasksPageSub({
        filters: filter,
        orFilters: orFilters,
        sorts: sorts
      }).then(res => {
        if (res.data.successFlg) {
          success(res.data);
        }
      });
    },
    noStowageSelsChange (sels) {
      this.sels = sels;
    },
    noStowageSelect (sel, row) {
      this.parentSelect('noStowageTable', sel, row);
    },
    parentSelect (ref, sel, row) {
      let self = this;
      let ids = sel.map(i => i.id);
      const traverseCheckedChilNodes = function (node) {
        const childNodes = node.children;
        if (childNodes) {
          childNodes.forEach((child) => {
            if (ids.indexOf(child.id) === -1) {
              self.$refs[ref].toggleRowSelection(child);
            }
            traverseCheckedChilNodes(child);
          });
        }
      };
      const traverseUnCheckChilNodes = function (node) {
        const childNodes = node.children;
        if (childNodes) {
          childNodes.forEach((child) => {
            if (ids.indexOf(child.id) > -1) {
              self.$refs[ref].toggleRowSelection(child, false);
            }
            traverseUnCheckChilNodes(child);
          });
        }
      };

      const traverseParent = function (node, checked = true) {
        let id = node.$pid;
        while (id) {
          if (checked) {
            let children = sel.filter(item => {
              return item.$pid === id;
            });
            let parents = self.$refs[ref].store.states.data.filter(item => {
              return item.id === id;
            });
            if (parents.length > 0 && parents[0].children.length === children.length) {
              self.$refs[ref].toggleRowSelection(parents[0]);
              id = parents[0].$pid;
            } else {
              id = null;
            }
          } else {
            let parents = sel.filter(item => {
              return item.id === id;
            });
            if (parents.length > 0) {
              self.$refs[ref].toggleRowSelection(parents[0], false);
              id = parents[0].$pid;
            } else {
              id = null;
            }
          }
        }
      };
      if (sel.indexOf(row) > -1) {
        if (row.children) {
          traverseCheckedChilNodes(row);
        } else {
          traverseParent(row, true);
        }
      } else {
        if (row.children) {
          traverseUnCheckChilNodes(row);
        } else {
          traverseParent(row, false);
        }
      }
    },
    noStowageQuery () {
      this.noStowageSearch(this.$ue.objToFilter(this.searchCondition));
    },
    noStowageReset () {
      this.$ue.resetObjNull(this.searchCondition);
      this.noStowageShipmentsDaterange = [];
      this.noStowageOrganizations = [];
    },
    noStowageSearch (filters) {
      this.listLoading = true;
      if (this.orderType) {
        this.loadShipmentsRegionAndNum('ISNULL_childrenNum;ISNULL_LEFT_loadingListTrunkTask.id;' + filters, data => {
          this.listLoading = false;
          this.tableData = data;
        });
      } else {
        this.loadSendRegionAndNum('ISNULL_childrenNum;ISNULL_LEFT_loadingListTrunkTask.id;' + filters, data => {
          this.listLoading = false;
          this.tableData = data;
        });
      }
    },
    loadSendRegionAndNum (filters, fn) {
      sendRegionAndNum({
        filters: filters
      }).then(res => {
        if (res.data.successFlg === true) {
          fn(res.data.detailModelList.map(item => {
            item.type = 'group';
            item.depth = 0;
            return item;
          }));
        }
      });
    },
    loadShipmentsRegionAndNum (filters, fn) {
      shipmentsRegionAndNum({
        filters: filters
      }).then(res => {
        if (res.data.successFlg === true) {
          fn(res.data.detailModelList.map(item => {
            item.type = 'group';
            item.depth = 0;
            return item;
          }));
        }
      });
    }
  },
  mounted () {
    this.$store.commit('initOrganizations');
  }
};
</script>
